package com.example.demo.controller;

import com.example.demo.dto.OrderDTO;
import com.example.demo.dto.OrderDetailDTO;
import com.example.demo.entity.OrdersManagement;
import com.example.demo.service.GoodsService;
import com.example.demo.service.OrdersManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单管理 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/ordersManagement")
public class OrdersManagementController {
    @Autowired
    private OrdersManagementService ordersManagementService;

    @Autowired
    private GoodsService goodsService;

    // 获取买家订单
    @GetMapping("/buyer/{buyerId}")
    public ResponseEntity<List<OrderDTO>> getBuyerOrders(@PathVariable Integer buyerId) {
        List<OrderDTO> orders = ordersManagementService.getBuyerOrdersWithDetails(buyerId);
        return ResponseEntity.ok(orders);
    }
    // 获取卖家订单
    @GetMapping("/seller/{sellerId}")
    public ResponseEntity<List<OrderDTO>> getSellerOrders(@PathVariable Integer sellerId) {
        List<OrderDTO> orders = ordersManagementService.getSellerOrdersWithDetails(sellerId);
        return ResponseEntity.ok(orders);
    }

    // 获取订单详情的接口
    @GetMapping("/detail/{orderId}")
    public ResponseEntity<OrderDetailDTO> getOrderDetail(@PathVariable Integer orderId) {
        OrderDetailDTO orderDetail = ordersManagementService.getOrderDetailById(orderId);
        if (orderDetail == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        return ResponseEntity.ok(orderDetail);
    }

    // 取消订单
    @PostMapping("/cancel/{orderId}")
    public ResponseEntity<String> cancelOrder(@PathVariable Integer orderId) {
        if (ordersManagementService.cancelOrder(orderId)) {
            return ResponseEntity.ok("订单取消成功");
        }
        return ResponseEntity.badRequest().body("订单取消失败");
    }

    // 确认收货
    @PostMapping("/confirm/{orderId}")
    public ResponseEntity<String> confirmOrder(@PathVariable Integer orderId) {
        if (ordersManagementService.confirmOrder(orderId)) {
            return ResponseEntity.ok("订单确认成功");
        }
        return ResponseEntity.badRequest().body("订单确认失败");
    }

    // 更新订单状态
    @PutMapping("/updateStatus")
    public ResponseEntity<String> updateOrderStatus(@RequestBody OrdersManagement order) {
        try {
            String result = ordersManagementService.updateOrderStatus(order);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("更新订单状态失败: " + e.getMessage());
        }
    }
}


